package seed

import (
	"strings"
	"wms/internal/model"
	"wms/pkg/database"
	"wms/pkg/logger"

	"go.uber.org/zap"
)

// isDuplicateEntryError 检查错误是否是常见的主键/唯一约束冲突错误
func isDuplicateEntryError(err error) bool {
	if err == nil {
		return false
	}
	errStr := strings.ToLower(err.Error())
	// 检查 MySQL 和 PostgreSQL 的常见错误信息
	return strings.Contains(errStr, "duplicate entry") || strings.Contains(errStr, "unique constraint")
}

// InitMenus 初始化菜单数据 - 简化版
func InitMenus() error {
	db := database.GetDB()

	// 菜单数据 (v2 - 保持不变)
	menus := []*model.Menu{
		// 1. 仪表盘 (ID: 1-3)
		{ ID: 1, ParentID: 0, Name: "Dashboard", Path: "/dashboard", Component: "Layout", Title: "仪表盘", Icon: "dashboard", Sort: 1, Status: 1 },
		{ ID: 2, ParentID: 1, Name: "Workbench", Path: "workbench", Component: "dashboard/workbench", Title: "工作台", Icon: "desktop", Sort: 1, Status: 1 },
		{ ID: 3, ParentID: 1, Name: "Report", Path: "report", Component: "dashboard/report", Title: "统计报表", Icon: "file", Sort: 2, Status: 1 },
		// 2. 权限管理 (ID: 4-6)
		{ ID: 4, ParentID: 0, Name: "User", Path: "/user", Component: "Layout", Title: "权限管理", Icon: "user-group", Sort: 2, Status: 1 },
		{ ID: 5, ParentID: 4, Name: "UserMgmt", Path: "user-mgmt", Component: "user/user-mgmt", Title: "用户管理", Icon: "user", Sort: 1, Status: 1 },
		{ ID: 6, ParentID: 4, Name: "RoleCfg", Path: "role-cfg", Component: "user/role-cfg", Title: "角色管理", Icon: "team", Sort: 2, Status: 1 },
		// 3. 基础设置 (ID: 7-14)
		{ ID: 7, ParentID: 0, Name: "BasicSettings", Path: "/basic-settings", Component: "Layout", Title: "基础设置", Icon: "setting", Sort: 3, Status: 1 },
		{ ID: 8, ParentID: 7, Name: "CargoInfo", Path: "cargo-info", Component: "settings/cargo-info", Title: "货物信息", Icon: "tag", Sort: 1, Status: 1 },
		{ ID: 9, ParentID: 7, Name: "CargoCategoryMgmt", Path: "cargo-category", Component: "settings/cargo-category", Title: "货物分类", Icon: "menu", Sort: 2, Status: 1 },
		{ ID: 10, ParentID: 7, Name: "SupplierProfile", Path: "supplier-profile", Component: "settings/supplier-profile", Title: "供应商资料", Icon: "apartment", Sort: 3, Status: 1 },
		{ ID: 11, ParentID: 7, Name: "CustomerProfile", Path: "customer-profile", Component: "settings/customer-profile", Title: "客户资料", Icon: "user-group", Sort: 4, Status: 1 },
		{ ID: 12, ParentID: 7, Name: "Logistics", Path: "logistics", Component: "settings/logistics", Title: "物流管理", Icon: "export", Sort: 5, Status: 1 },
		{ ID: 13, ParentID: 7, Name: "WarehouseManagement", Path: "warehouses", Component: "settings/WarehouseManagement", Title: "仓库管理", Icon: "home", Sort: 6, Status: 1 },
		{ ID: 14, ParentID: 7, Name: "LocationManagement", Path: "locations", Component: "settings/LocationManagement", Title: "库位管理", Icon: "environment", Sort: 7, Status: 1 },
		// 4. 库存管理 (ID: 15-18)
		{ ID: 15, ParentID: 0, Name: "Inventory", Path: "/inventory", Component: "Layout", Title: "库存管理", Icon: "database", Sort: 4, Status: 1 },
		{ ID: 16, ParentID: 15, Name: "InventoryQuery", Path: "query", Component: "inventory/InventoryQuery", Title: "库存查询", Icon: "search", Sort: 1, Status: 1 },
		{ ID: 17, ParentID: 15, Name: "InventoryAlerts", Path: "alerts", Component: "inventory/InventoryAlerts", Title: "库存预警", Icon: "alert", Sort: 2, Status: 1 },
		{ ID: 18, ParentID: 15, Name: "InventoryCount", Path: "count", Component: "inventory/InventoryCount", Title: "库存盘点", Icon: "ordered-list", Sort: 3, Status: 1 },
		// 5. 入库管理 (ID: 19, 20, 101, 102)
		{ ID: 19, ParentID: 0, Name: "Inbound", Path: "/inbound", Component: "Layout", Title: "入库管理", Icon: "import", Sort: 5, Status: 1 },
		{ ID: 20, ParentID: 19, Name: "InboundOrderList", Path: "orders", Component: "inbound/InboundOrderList", Title: "入库单列表", Icon: "file", Sort: 1, Status: 1 },
		{ ID: 101, ParentID: 19, Name: "ReceivingOperation", Path: "receive/:id", Component: "inbound/ReceivingOperation", Title: "收货操作", Icon: "", Sort: 3, Status: 1, Hidden: true }, // 收货页面
		{ ID: 102, ParentID: 19, Name: "PutawayOperation", Path: "putaway/:id", Component: "inbound/PutawayOperation", Title: "上架操作", Icon: "", Sort: 4, Status: 1, Hidden: true }, // 上架页面
		
		// 6. 出库管理 (ID: 21, 22, 103, 104)
		{ ID: 21, ParentID: 0, Name: "Outbound", Path: "/outbound", Component: "Layout", Title: "出库管理", Icon: "export", Sort: 6, Status: 1 },
		{ ID: 22, ParentID: 21, Name: "OutboundOrderList", Path: "orders", Component: "outbound/OutboundOrderList", Title: "出库单列表", Icon: "file", Sort: 1, Status: 1 },
		// --- 新增出库操作菜单 ---
		{ ID: 103, ParentID: 21, Name: "PickingOperation", Path: "pick/:id", Component: "outbound/PickingOperation", Title: "拣货操作", Icon: "", Sort: 2, Status: 1, Hidden: true }, // 拣货页面
		{ ID: 104, ParentID: 21, Name: "ShippingOperation", Path: "ship/:id", Component: "outbound/ShippingOperation", Title: "发货操作", Icon: "", Sort: 3, Status: 1, Hidden: true }, // 发货页面
		// --- 新增结束 ---
		// 7. 关于系统 (ID: 23-25)
		{ ID: 23, ParentID: 0, Name: "About", Path: "/about", Component: "Layout", Title: "关于系统", Icon: "info-circle", Sort: 7, Status: 1 },
		{ ID: 24, ParentID: 23, Name: "SystemLog", Path: "log", Component: "about/system-log", Title: "系统日志", Icon: "file-text", Sort: 1, Status: 1 },
		{ ID: 25, ParentID: 23, Name: "SystemInfo", Path: "info", Component: "about/system-info", Title: "系统信息", Icon: "laptop", Sort: 2, Status: 1 },
		// 8. 个人中心 (ID: 26-27)
		{ ID: 26, ParentID: 0, Name: "PersonalRoute", Path: "/personal", Component: "Layout", Title: "个人中心", Icon: "idcard", Sort: 8, Status: 1, Hidden: true },
		{ ID: 27, ParentID: 26, Name: "PersonalInfo", Path: "", Component: "user/personal", Title: "个人中心", Icon: "user", Sort: 1, Status: 1, Hidden: true },
	}

	// 插入菜单数据 (使用 Create)
	for _, menu := range menus {
		if err := db.Create(menu).Error; err != nil {
			// 检查是否是主键冲突错误，如果是，则忽略
			if isDuplicateEntryError(err) {
				continue // 继续下一个菜单
			}
			logger.Error("创建菜单数据失败", zap.Error(err), zap.String("menu", menu.Title))
			return err
		}
	}

	// 初始化角色菜单关联数据
	if err := initRoleMenusSimplified(); err != nil {
		return err
	}

	logger.Info("菜单数据初始化成功 (简化版)")
	return nil
}

// initRoleMenusSimplified 初始化角色菜单关联数据 - 简化版
func initRoleMenusSimplified() error {
	db := database.GetDB()

	// 管理员角色 (RoleID: 1) 拥有所有菜单权限
	adminRoleID := uint(1)
	var allMenus []model.Menu
	if err := db.Find(&allMenus).Error; err != nil {
		logger.Error("查询所有菜单失败", zap.Error(err))
		return err
	}
	for _, menu := range allMenus {
		roleMenu := &model.RoleMenu{RoleID: adminRoleID, MenuID: menu.ID}
		if err := db.Create(roleMenu).Error; err != nil {
            // 忽略主键冲突错误
			if !isDuplicateEntryError(err) {
                logger.Error("为管理员分配菜单权限失败", zap.Error(err), zap.Uint("menuID", menu.ID))
                // 根据需要决定是否返回错误，这里选择继续
            }
		}
	}

	// 员工角色 (RoleID: 2) 权限 - 排除权限管理(4-6)和基础设置(7-14)
	employeeRoleID := uint(2)
	employeeMenuIDs := []uint{
		1, 2, 3,          // 仪表盘
		15, 16, 17, 18,    // 库存管理
		19, 20,          // 入库管理
		21, 22,          // 出库管理
		23, 24, 25,       // 关于系统 (员工可访问所有子项)
		26, 27,          // 个人中心
	}

	// 为员工分配权限 (使用 Create, 忽略冲突)
	for _, menuID := range employeeMenuIDs {
		roleMenu := &model.RoleMenu{RoleID: employeeRoleID, MenuID: menuID}
		if err := db.Create(roleMenu).Error; err != nil {
            // 忽略主键冲突错误
            if !isDuplicateEntryError(err) {
                logger.Error("为员工分配菜单权限失败", zap.Error(err), zap.Uint("menuID", menuID))
                // 根据需要决定是否返回错误，这里选择继续
            }
		}
	}

	return nil
}
